package org.learn.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.learn.domain.User;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 用户登录操作
     *
     * @param user
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, String rememberMe, HttpServletRequest request, Model model) {
        //验证码校验
        if (!StringUtils.isEmpty(request.getAttribute("captcha"))){
            String verifyCode = (String)request.getAttribute("captcha");
            if("captchaError".equals(verifyCode)){
                model.addAttribute("msg", "验证码错误");
                return "login";
            }

        }


        Subject subject = SecurityUtils.getSubject();
        //封装请求的用户信息。
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        //勾选记住我功能
        if (null != rememberMe && "1".equals(rememberMe)) {
            token.setRememberMe(true);
        }
        try {
            //将封装的用户信息传递到Realm
            subject.login(token);
            //登录成功
            User dbUser = (User) subject.getPrincipal();
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }
}
